﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FortuneCat.WebUI.Models;
using System.Configuration;
using FortuneCat.Domain.Concrete;

namespace FortuneCat.WebUI.Infrastructure {
    public class AccountModelBinder : IModelBinder {
        private const string _accountSessionKey = "_account";

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
            if (bindingContext.Model != null) {
                throw new InvalidOperationException("Cannot update instances");
            }

            if (!controllerContext.HttpContext.User.Identity.IsAuthenticated) {
                return null;
            }

            AccountInfo account = (AccountInfo)controllerContext.HttpContext.Session[_accountSessionKey];
            if (account == null) {
                string connectionString = ConfigurationManager.ConnectionStrings["EFDbContext"].ConnectionString;
                EFUserRepository userRepository = new EFUserRepository();
                account = new AccountInfo() {
                    User = userRepository.Items.Where(x => x.UserName.ToLower() == controllerContext.HttpContext.User.Identity.Name.ToLower()).FirstOrDefault(),
                    Identity = controllerContext.HttpContext.User.Identity
                };
            }
            return account;
        }
    }
}